package com.freecloud.framework.interceptor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.freecloud.framework.config.ClientConfig;
import com.freecloud.framework.constant.Constant;
import com.freecloud.framework.exceptions.RRException;
import com.freecloud.framework.utils.DESUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import static com.freecloud.framework.constant.Constant.CLIENT_TOKEN_PASSWORD_KEY;

/**
 * Created by ace on 2017/9/12.
 */
public class ClientTokenInterceptor implements RequestInterceptor {
    private Logger logger = LoggerFactory.getLogger(ClientTokenInterceptor.class);
    @Autowired
    private ClientConfig clientConfig;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            requestTemplate.header(clientConfig.getClientTokenHeader(), CreateClientToken(clientConfig.getClientId(),clientConfig.getClientSecret()));
        } catch (Exception e) {
            logger.error("client token error : " ,e);
        }
    }

    /**
     * 生成Client TOKEN密钥
     * @param clientId
     * @param clientSecret
     * @return
     */
    private String CreateClientToken(String clientId,String clientSecret){
        if(StrUtil.isEmpty(clientId) || StrUtil.isEmpty(clientSecret)){
            throw new RRException("必须参数不能为空！");
        }

        String password = String.format("%s" + Constant.CLIENT_TOKEN_PASSWORD_PARTITION + "%s" + Constant.CLIENT_TOKEN_PASSWORD_PARTITION + "%s",clientId,clientSecret, DateUtil.date().getTime());
        return DESUtils.encode(CLIENT_TOKEN_PASSWORD_KEY,password);
    }
}
